package com.group3.service.impl;

import com.group3.entity.*;
import com.group3.dao.*;
import com.group3.service.BehaviorCollectService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class BehaviorCollectServiceImpl implements BehaviorCollectService {

    @Resource
    private BrowseBehaviorMapper browseBehaviorMapper;

    @Resource
    private ClickBehaviorMapper clickBehaviorMapper;

    @Resource
    private PurchaseBehaviorMapper purchaseBehaviorMapper;

    @Resource
    private FavoriteBehaviorMapper favoriteBehaviorMapper;

    @Resource
    private CommentBehaviorMapper commentBehaviorMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public void recordBrowse(BrowseBehavior behavior) {
        behavior.setCreateTime(LocalDateTime.now());
        browseBehaviorMapper.insert(behavior);
        updateUserProfileCache(behavior.getUserId());
    }

    @Override
    public void recordClick(ClickBehavior behavior) {
        behavior.setCreateTime(LocalDateTime.now());
        clickBehaviorMapper.insert(behavior);
        updateUserProfileCache(behavior.getUserId());
    }

    @Override
    public void recordPurchase(PurchaseBehavior behavior) {
        behavior.setCreateTime(LocalDateTime.now());
        purchaseBehaviorMapper.insert(behavior);
        updateUserProfileCache(behavior.getUserId());
    }

    @Override
    public void recordFavorite(FavoriteBehavior behavior) {
        behavior.setCreateTime(LocalDateTime.now());
        favoriteBehaviorMapper.insert(behavior);
        updateUserProfileCache(behavior.getUserId());
    }

    @Override
    public void recordComment(CommentBehavior behavior) {
        behavior.setCreateTime(LocalDateTime.now());
        commentBehaviorMapper.insert(behavior);
        updateUserProfileCache(behavior.getUserId());
    }

    private void updateUserProfileCache(Long userId) {
        String key = "user_profile:" + userId;
        redisTemplate.delete(key);
        // 设置30天过期
        redisTemplate.expire(key, 30, TimeUnit.DAYS);
    }
}
